package com.warski.wonderfires.utils.json;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by xuhaiping on 2020/7/13.
 */
public class JsonUtils {
    private static Gson gson = null;

    static {
        init();
    }

    private static void init() {
        gson = new GsonBuilder()
                .registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
            @Override
            public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                if(src == src.longValue()){
                    return new JsonPrimitive(src.longValue());
                }
                return new JsonPrimitive(src);
            }
        }).create();
    }

    public static String toJson(Object object) {
        return gson.toJson(object);
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        return gson.fromJson(json, classOfT);
    }

    public static <T> T fromJson(String json, Type typeOfT) {
        return gson.fromJson(json, typeOfT);
    }
}
